package shop.up.order.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.up.cart.client.CartFeignClient;
import shop.up.common.result.Result;
import shop.up.common.util.AuthContextHolder;
import shop.up.model.cart.CartInfo;
import shop.up.model.order.OrderDetail;
import shop.up.model.order.OrderInfo;
import shop.up.model.user.UserAddress;
import shop.up.order.service.OrderService;
import shop.up.product.client.ProductFeignClient;
import shop.up.user.client.UserFeignClient;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: Tizzy
 * @Date: 2023/4/13 20:40
 */
@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    private CartFeignClient cartFeignClient;

    @Resource
    private OrderService orderService;

    @Resource
    private ProductFeignClient productFeignClient;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 确认订单
     * @param request
     * @return
     */
    @GetMapping("auth/trade")
    public Result<Map<String, Object>> trade(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //获取用户地址
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);

        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (CartInfo info : cartCheckedList) {
            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setSkuId(info.getSkuId());
            orderDetail.setSkuName(info.getSkuName());
            orderDetail.setImgUrl(info.getImgUrl());
            orderDetail.setSkuNum(info.getSkuNum());
            orderDetail.setOrderPrice(info.getSkuPrice());
            // 添加到集合
            orderDetailList.add(orderDetail);
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(orderDetailList);
        orderInfo.sumTotalAmount();
        Map<String,Object> result = new HashMap<>();
        result.put("userAddressList", userAddressList);
        result.put("detailArrayList", orderDetailList);
        // 保存总金额
        result.put("totalNum", orderDetailList.size());
        result.put("totalAmount", orderInfo.getTotalAmount());
        // 获取流水号
        String tradeNo = orderService.getTradeNo(userId);
        result.put("tradeNo", tradeNo);

        return Result.ok(result);

    }

    /* 提交订单
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        // 获取到用户Id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));

        // 获取前台页面的流水号
        String tradeNo = request.getParameter("tradeNo");
        // 调用服务层的比较方法
        boolean flag = orderService.checkTradeCode(userId, tradeNo);
        if (!flag) {
            // 比较失败！
            return Result.fail().message("不能重复提交订单！");
        }
        //  删除流水号
        orderService.deleteTradeNo(userId);

//        // 验证库存：
//        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
//        for (OrderDetail orderDetail : orderDetailList) {
//            // 验证库存：
//            boolean result = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
//            if (!result) {
//                return Result.fail().message(orderDetail.getSkuName() + "库存不足！");
//            }
//            // 验证价格：
//            BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
//            if (orderDetail.getOrderPrice().compareTo(skuPrice) != 0) {
//                // 重新查询价格！
//                cartFeignClient.loadCartCache(userId);
//                return Result.fail().message(orderDetail.getSkuName() + "价格有变动！");
//            }
//        }

        List<String> errorList = new ArrayList<>();
        List<CompletableFuture> futureList = new ArrayList<>();
        // 验证库存：
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            CompletableFuture<Void> checkStockCompletableFuture = CompletableFuture.runAsync(() -> {
                // 验证库存：
                boolean result = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                if (!result) {
                    errorList.add(orderDetail.getSkuName() + "库存不足！");
                }
            }, threadPoolExecutor);
            futureList.add(checkStockCompletableFuture);

            CompletableFuture<Void> checkPriceCompletableFuture = CompletableFuture.runAsync(() -> {
                // 验证价格：
                BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                if (orderDetail.getOrderPrice().compareTo(skuPrice) != 0) {
                    // 重新查询价格！
                    cartFeignClient.loadCartCache(userId);
                    errorList.add(orderDetail.getSkuName() + "价格有变动！");
                }
            }, threadPoolExecutor);
            futureList.add(checkPriceCompletableFuture);
        }
        //合并线程
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();
        if(errorList.size() > 0) {
            return Result.fail().message(StringUtils.join(errorList, ","));
        }

        // 验证通过，保存订单！
        Long orderId = orderService.saveOrderInfo(orderInfo);
        return Result.ok(orderId);
    }

}
